package com.bwie.auth.service.impl;

import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.remote.system.RemoteSystemService;
import com.bwie.common.result.Result;
import com.bwie.common.utils.IdUtils;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author：ShenJiaFeng
 * @Package：com.bwie.auth.service.impl
 * @Project：zg6_week11
 * @name：AuthServiceImpl
 * @Date：2024/4/25 9:27
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private RemoteSystemService remoteSystemService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<UserResponse> login(UserRequest userRequest) {
        Result<User> byUserName = remoteSystemService.findByUserName(userRequest.getUserName());
        Assert.isTrue(byUserName.isSuccess(),"登录失败");
        User user = byUserName.getData();
        Assert.notNull(user,"用户不存在");
        Assert.isTrue(userRequest.getUserPwd().equals(user.getUserPwd()),"密码错误");
        HashMap<String, Object> map = new HashMap<>();
        String userKey = IdUtils.genId();
        map.put(JwtConstants.USER_KEY,userKey);
        map.put(JwtConstants.DETAILS_USER_ID,user.getUserId());
        map.put(JwtConstants.DETAILS_USERNAME,user.getUserName());
        String token = JwtUtils.createToken(map);
        redisCache.setCacheObject(
                TokenConstants.LOGIN_TOKEN_KEY+userKey,
                user,
                TokenConstants.EXPIRATION,
                TimeUnit.MINUTES
        );
        return Result.success(
                UserResponse.
                        builder()
                        .token(token)
                        .outTime(TokenConstants.EXPIRATION)
                        .build()
        );
    }

    @Override
    public User userInfo() {
        return redisCache.getCacheObject(
                TokenConstants.LOGIN_TOKEN_KEY+request.getHeader(JwtConstants.USER_KEY)
        );
    }
}
